<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写promise</title>
</head>

<body>

</body>
<script>
    let p1 = new Promise((resolve, reject) => {
        resolve("p1")
        // reject("p1")
    })
    let p2 = new Promise((resolve, reject) => {
        // resolve("p2")
        reject("p2")
    })

    // 自带promise.all
    // Promise.all([p1, p2]).then(result => {
    //     console.log(result)
    // }, reason => {
    //     console.log(reason)
    // })



    // 手写promise.all
    Promise._all = function (array) {
        console.log("promise._all")
        return new Promise((resolve, reject) => {
            let result = []
            let count = 0
            for (let i = 0; i < array.length; i++) {
                array[i].then(data => {
                    result[i] = data
                    count++
                    if (count == array.length) {
                        resolve(result)
                    }
                }, reason => {
                    reject(reason)
                })
            }
        })
    }
    Promise._all([p1, p2])
        .then(
            result => console.log(result),
            reason => console.log(reason)
        )
        .catch(err => {
            console.log(err)
        })


</script>

</html>